﻿using Ldt.InformationUnit.Common;
using LdtDataEngin.ModuleDetail.CaseElmentOpt;
using LdtDataEngin.ModuleDetail.CommonModule.EvidenceElementOptimize;
using LdtDataEngin.ModuleDetail.CommonModule.XmlCodeCommon;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.ConfigXmlLoad;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.Moudle
{
    /// <summary>
    /// 案件优选模块
    /// </summary>
    public class MoudleCaseOptimize : MoudleBase
    {
        private IMoudle _moudle;
        private static string _moudleResult;
        public MoudleCaseOptimize(IMoudle moudle)
        {
            _moudle = moudle;
        }
        public override void MoudleHandle(DataContext dataContext)
        {
            //执行当前模块的相关业务逻辑；违法行为详情
            string moudleName = typeof(MoudleCaseOptimize).FullName;
            moudleName += "_" + this.GetHashCode();
            // 设置模块进度
            dataContext.InteractiveShow.ModuleProcessShow?.Invoke(moudleName, 0, dataContext.InteractiveShow.inputParameterModel);
            // 创建计时器
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                dataContext.InteractiveShow.LogShow("***************************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--->开始执行案件要素优选模块*****************************");
                XmlCodeStartModel xmlCodeStartModel = new XmlCodeStartModel() { dataContext = dataContext };
                var configModel = dataContext.DataLayerSys.GetConfigModel(moudleName);
                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
                if (xmlCodeStartModel.Extract(configModel))
                {
                    CaseOptimization caseOptimization = new CaseOptimization(dataContext, moudleName);
                    if (xmlCodeStartModel.Extract(configModel))
                    {
                        if (dataContext.DataLayerAns.dataContentList != null && dataContext.DataLayerAns.dataContentList.Any())
                        {
                            BackOptimization(dataContext, moudleName, caseOptimization);
                        }
                        else
                        {
                            caseOptimization.Optimization();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                dataContext.InteractiveShow.LogShow("案件要素优选模块错误：" + ex.ToString());
            }
            
            // 设置模块进度*用时"+ stopwatch.Elapsed.TotalMilliseconds.ToString("0") + "
            stopwatch.Stop();
            _moudleResult = dataContext.DataLayerOpt.OptimizationXml.OuterXml;
            dataContext.InteractiveShow.ModuleProcessShow?.Invoke(moudleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100, dataContext.InteractiveShow.inputParameterModel);
            dataContext.InteractiveShow.LogShow("***************************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--->案件要素优选模块执行完成***用时" + stopwatch.Elapsed.TotalMilliseconds.ToString("0") + "***************************");
            //执行完毕调用下一个模块；
            _moudle.MoudleHandle(dataContext);
        }

        /// <summary>
        /// 回填信息
        /// </summary>
        public void BackOptimization(DataContext dataContext, string moudleName, CaseOptimization caseOptimization)
        {
            foreach (var content in dataContext.DataLayerAns.dataContentList)
            {
                if (!string.IsNullOrEmpty(content.Content) && !string.IsNullOrEmpty(content.SourceCode))
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    try
                    {
                        if(content.IsEvidence==1)
                            dataContext.DataLayerAns.SourceCode = "evidencedata";
                        string messages = HttpHelp.DeCodeBase64new(65001, content.Content.Replace('"', ' ')).Replace("&lt;", "<").Replace("&gt;", ">");
                        dynamic dys = JsonConvert.DeserializeObject<dynamic>(messages);
                        string changeStr = dys.changedata.ToString();
                        List<ChangeDataModel> changeDataModelList = JsonConvert.DeserializeObject<List<ChangeDataModel>>(changeStr);
                        dataContext.DataLayerAns.Shujuneirong.Shujuid = Snowflake.Instance().GetId().ToString();
                        dataContext.DataLayerAns.Shujuneirong.Sf_id = content.sfid;
                        dataContext.DataLayerAns.Shujuneirong.Shujuyuanbianhao = content.SourceCode;
                        //TODO:ZSW 证据与事实要素关系建立
                        DataOptimization(dataContext, changeDataModelList, moudleName, caseOptimization, content.IsEvidence);
                    }
                    catch (Exception ex)
                    {
                        dataContext.InteractiveShow.LogShow("当前数据源：" + content.SourceCode + "分析失败！");
                    }
                    stopwatch.Stop();
                    dataContext.InteractiveShow.LogShow("当前数据源：" + content.SourceCode + "案件分析时长" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"));
                }
            }
        }

        /// <summary>
        /// 流程回填信息
        /// </summary>
        /// <param name="dataContext">上下文</param>
        /// <param name="changeDataModelList">回填数据</param>
        /// <param name="moudleName">模块名称</param>
        /// <param name="caseOptimization">优选配置</param>
        /// <param name="isEvidence">是否证据 1.是 0.否</param>
        //TODO:ZSW 证据与事实要素关系建立
        public void DataOptimization(DataContext dataContext, List<ChangeDataModel> changeDataModelList, string moudleName, CaseOptimization caseOptimization, int isEvidence = 0)
        {
            foreach (ChangeDataModel changeDataModel in changeDataModelList)
            {
                try
                {
                    ChangeDataModel changeData = JsonConvert.DeserializeObject<ChangeDataModel>(JsonConvert.SerializeObject(changeDataModel));
                    if (changeDataModel.ChangeType.ToLower() == "a_attr" || changeDataModel.ChangeType.ToLower() == "m_attr")
                    {
                        caseOptimization.A_attrClass(changeDataModel);
                    }
                    else if (changeDataModel.ChangeType.ToLower() == "a_node")
                    {
                        string nodeValue = HttpHelp.DeCodeBase64new(65001, changeDataModel.ChangeValue.Trim());
                        XmlDocument nodeDocument = new XmlDocument();
                        nodeDocument.LoadXml(nodeValue);
                        XmlNode xmlNode = nodeDocument.SelectSingleNode("descendant-or-self::分人员要素/child::*[1]");
                        if (xmlNode != null)
                        {
                            changeData.XmlPath = "";
                            changeData.ChangeValue = HttpHelp.EncodeBase64(xmlNode.OuterXml);
                            dataContext.DataLayerAns.causeChangeDataModelList.Add(changeData);
                            nodeValue = nodeValue.Replace(xmlNode.OuterXml, "");
                            changeDataModel.ChangeValue = nodeValue;
                        }
                        XmlNode judgeXmlNode = nodeDocument.SelectSingleNode("descendant-or-self::法官确认要素/child::*[1]");
                        if (judgeXmlNode != null)
                        {
                            XmlDocument judgeDoc = new XmlDocument();
                            judgeDoc.LoadXml(judgeXmlNode.OuterXml);
                            changeData.XmlPath = "";
                            changeData.ChangeValue = HttpHelp.EncodeBase64(judgeXmlNode.OuterXml);
                            //加载法官确认要素数据
                            caseOptimization.LoadJudgeConfirmData(changeData);
                            nodeValue = nodeValue.Replace(judgeXmlNode.OuterXml, "");
                            changeDataModel.ChangeValue = nodeValue;
                        }
                        if (!string.IsNullOrEmpty(changeDataModel.ChangeValue))
                        {
                            caseOptimization.A_nodeClass(changeDataModel);
                        }
                    }
                    else if (changeDataModel.ChangeType.ToLower() == "d_attr")
                    {
                        caseOptimization.D_attrClass(changeDataModel);
                    }
                    else if (changeDataModel.ChangeType.ToLower() == "d_node")
                    {
                        caseOptimization.D_nodeClass(changeDataModel);
                    }
                    if (changeDataModel.XmlPath.IndexOf("分人员要素") > -1)
                    {
                        string value = changeDataModel.XmlPath.Split("分人员要素")[1];
                        changeData.XmlPath = value;
                        dataContext.DataLayerAns.causeChangeDataModelList.Add(changeData);
                    }
                }
                catch (Exception ex)
                {
                    dataContext.InteractiveShow.LogShow(dataContext.DataLayerAns.SourceCode + "数据源优选错误");
                }

            }
        }

        /// <summary>
        /// 模块处理结果
        /// </summary>
        /// <returns></returns>
        public static HandleResultModel MoudleHandleResult()
        {
            HandleResultModel resultModel = new HandleResultModel();
            if (!string.IsNullOrWhiteSpace(_moudleResult))
            {
                resultModel.ResultType = "1";
                resultModel.ResultData = _moudleResult;
            }
            return resultModel;
        }
    }
}
